package cn.com.dashihui.pay.wx.kit;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpsRequest{
	private static final Logger log = LoggerFactory.getLogger(HttpsRequest.class);
    //连接超时时间，默认10秒
    private int socketTimeout = 10000;
    //传输超时时间，默认30秒
    private int connectTimeout = 30000;
    //请求器的配置
    private RequestConfig requestConfig;
    //HTTP请求器
    private CloseableHttpClient httpClient;
    
    public HttpsRequest() throws UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, IOException {
        httpClient = HttpClients.custom().build();
        //根据默认超时限制初始化requestConfig
        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
    }
    public HttpsRequest(String certPath,String certPassword) throws UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, IOException {
    	KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File(certPath));//加载本地的证书进行https加密传输
        try {
        	keyStore.load(instream,certPassword.toCharArray());//设置证书密码
        } catch (CertificateException e) {
        	e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
        	e.printStackTrace();
        } finally {
        	instream.close();
        }
        
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, certPassword.toCharArray()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,new String[]{"TLSv1"},null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        //根据默认超时限制初始化requestConfig
        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
    }
    /**
     * 通过HTTPS向API提交POST请求
     * @param url API地址
     * @param xmlObj 要提交的XML数据对象
     * @return API返回数据
     */
    public String post(String api, Object data){
    	String result = null;
    	HttpPost httpPost = new HttpPost(api);

    	//将要提交给API的数据对象转换成XML格式数据Post给API
    	String postDataXML = UtilKit.getXMLFromObject(data);
    	System.out.println("API，POST过去的数据是："+postDataXML);
    	log.debug("API，POST过去的数据是："); 
    	log.debug(postDataXML);
    	
    	//得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
    	StringEntity postEntity = new StringEntity(postDataXML, "UTF-8");
    	httpPost.addHeader("Content-Type", "text/xml");
    	httpPost.setEntity(postEntity);
    	
    	//设置请求器的配置
    	httpPost.setConfig(requestConfig);
    	log.debug("executing request" + httpPost.getRequestLine());
    	
    	try {
    		HttpResponse response = httpClient.execute(httpPost);
    		HttpEntity entity = response.getEntity();
    		result = EntityUtils.toString(entity, "UTF-8");
    	} catch (ConnectionPoolTimeoutException e) {
    		log.debug("http get throw ConnectionPoolTimeoutException(wait time out)");
    	} catch (ConnectTimeoutException e) {
    		log.debug("http get throw ConnectTimeoutException");
    	} catch (SocketTimeoutException e) {
    		log.debug("http get throw SocketTimeoutException");
    	} catch (Exception e) {
    		log.debug("http get throw Exception");
    	} finally {
    		httpPost.abort();
    	}
    	return result;
    }
}
